"use client"
import { Switch } from "@/components/ui/switch"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { useEffect, useState, useRef } from 'react';
import axios from "axios";

export function ChatBarImage({ model, getUsage }) {
  const [messages, setMessages] = useState('');
  const [items, setItems] = useState([]);
  const messagesEndRef = useRef(null);

  const fileInputRef = useRef(null);

  const handleImageChange = async (event) => {
    const file = event.target.files[0];
    if (file) {
      console.log('Selected file:', file);
      const imageUrl = URL.createObjectURL(file);
      setItems((prevItems) => [...prevItems, { src: imageUrl, user: 'people' }]);
      let data = new FormData();
      data.append('image', file);
      try {
        const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/apiv2/${model}`, {
          method: 'POST',
          body: data
        });
        if (res.ok) {
          const blob = await res.blob();
          let responseImageUrl = URL.createObjectURL(blob);
          setItems((prevItems) => [...prevItems, { src: responseImageUrl, user: 'bot' }]);
          let config = {
            method: 'post',
            maxBodyLength: Infinity,
            url: `${process.env.NEXT_PUBLIC_API_URL}/api/yolo/task`
          };
          await axios.request(config)
          getUsage()
        } else {
          console.error('Error processing image');
        }
      } catch (error) {
        console.error('Error uploading image:', error);
      }

    }
  };


  const clickUploadImage = () => {
    //setItems((prevItems) => [...prevItems, { user: 'people', messageType: 'TEXT', message: messages }])
    fileInputRef.current.click();
  }

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  },[items])


  return (
    // h-full overflow-hidden px-2 pt-3 sm:px-[15px]

    <div className="bg-[#f1f2f2] overflow-auto flex flex-col h-full w-full rounded-lg ">
      <header className="flex items-center justify-between p-4 bg-white border-b">
        <div className="flex items-center space-x-2">
          <Disc3Icon className="w-6 h-6" />
          <span className="text-lg font-semibold">{model}</span>
        </div>
        <div className="flex items-center space-x-2">
          <span className="text-sm text-gray-500">Search</span>
          <Switch id="search" />
        </div>
      </header>
      <main className="flex-1 p-4 overflow-y-auto w-full">
        {items.map((item, index) => (
          // className="bg-[#fdf6e5] mt-4 w-10/12 flex items-start space-x-2 rounded-lg ${item.user === 'bot' ? 'justify-start' : 'justify-end'}"
          <div key={index} className={`w-4/5 p-4 mt-8 overflow-auto  items-start rounded-lg my-2 ${item.user === 'bot' ? 'bg-[#fdf6e5]' : ' text-right ml-auto bg-[#b9d7f3]'} `}>
            <img src={item.src} alt={`Uploaded ${index}`} className="object-cover rounded-lg" />
          </div>
        ))}
        <div ref={messagesEndRef} />
      </main>
      <footer className="flex justify-center items-center p-4 bg-white border-t">
        {/* <ActivityIcon className="w-6 h-6 text-gray-500" />
        <textarea ref={textareaRef} onKeyDown={handleKeyDown} onChange={handleChange} value={messages} placeholder="use Shift+Enter wrap a line" className="flex-1 mx-2 border-none focus:ring-0" style={{ height: `${height}px`, width: '100%' }}></textarea> */}
        <Button onClick={clickUploadImage} className="px-10 py-3  bg-[#bce5b6] text-white">upload image</Button>
        <input type="file" ref={fileInputRef} onChange={handleImageChange} className="hidden" accept="image/*" />
      </footer>
    </div>

  )
}

function ActivityIcon(props) {
  return (
    <svg
      {...props}
      xmlns="http://www.w3.org/2000/svg"
      width="24"
      height="24"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2" />
    </svg>
  )
}


function Disc3Icon(props) {
  return (
    <svg
      {...props}
      xmlns="http://www.w3.org/2000/svg"
      width="24"
      height="24"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <circle cx="12" cy="12" r="10" />
      <path d="M6 12c0-1.7.7-3.2 1.8-4.2" />
      <circle cx="12" cy="12" r="2" />
      <path d="M18 12c0 1.7-.7 3.2-1.8 4.2" />
    </svg>
  )
}


function XIcon(props) {
  return (
    <svg
      {...props}
      xmlns="http://www.w3.org/2000/svg"
      width="24"
      height="24"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M18 6 6 18" />
      <path d="m6 6 12 12" />
    </svg>
  )
}
